import localForage from 'localforage';

/*
类：本地缓存类
方法：
    setItem：加入缓存
    getItem：获取缓存
    cleanupExpiredData：批量清除过期缓存
    isItemExpired：判断是否过期


*/
class LocalCache {
  static setItem(key, value, expiredTime = 1) {
    let baseTime = 24 * 60 * 60 * 1000; //以天为基本单位
    let itemValue = {
      value: value,
      expiredTime: Date.now() + expiredTime * baseTime,
    };
    localForage.setItem(key, itemValue); //存入本地缓存
  }
  static async getItem(key) {
    let itemValue = await localForage.getItem(key);
    //过期，应该删除
    if (this.isItemExpired(itemValue)) {
      await localForage.removeItem(key);
      return null;
    }
    return itemValue;
  }

  static async cleanupExpiredData() {
    const keys = await localForage.keys(); //获取所有缓存
    for (const key of keys) {
      const item = await localForage.getItem(key);
      // 删除所有过期的缓存
      if (item && this.isItemExpired(item)) {
        await localForage.removeItem(key);
      }
    }
  }

  static isItemExpired(itemValue) {
    return itemValue == null || itemValue['expiredTime'] < Date.now();
  }
  //   根据传入的图层名字和算法对象，创建对应的缓存key，以缓存算法执行过程中产生的距离矩阵
  static createKeyforAlgorithm(layerName, algorithmObject) {
    let key = `distanceMatrix:${layerName}:${algorithmObject['name']}`;
    //判断算法对象中是否包含空间方向的计算
    if (
      'directionThreshold' in algorithmObject['params'] &&
      'directionWeight' in algorithmObject['params']
    ) {
      key = `${key}:${algorithmObject['params']['directionThreshold']}:${algorithmObject['params']['directionWeight']}`;
    }
    return key;
  }
}

export { LocalCache };
